﻿using System;
using System.Collections.Concurrent;

namespace HttpHelper
{
    /// <summary>
    ///
    /// </summary>
    public class WinHttpClient : RequestData
    {
        /// <summary>
        ///
        /// </summary>
        public WinHttpClient() : this(new CookieEasy())
        {
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="cookieEasy"></param>

        public WinHttpClient(CookieEasy cookieEasy) : base(new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase), cookieEasy)
        {
        }

        /// <summary>
        /// 获取 Header 存在返回 内容 不存在返回空文本
        /// </summary>
        /// <param name="header">header Name</param>
        /// <returns>string Header value</returns>
        public override string GetHeader(string header)
        {
            if (DefaultHeaders.TryGetValue(header, out string value))
            {
                return value;
            }
            return string.Empty;
        }

        /// <summary>
        /// 添加或替换HTTP协议头（必须在Open后使用）
        /// </summary>
        /// <param name="header">协议头名称</param>
        /// <param name="value">协议头内容 空文本为删除此协议头</param>
        public override void SetRequestHeader(string header, string value = null)
        {
            if (string.IsNullOrEmpty(header)) return;
            // 判断Value 是否为空 如为空  则删除 Header
            if (string.IsNullOrEmpty(value))
                DefaultHeaders.TryRemove(header, out value);
            //如不为空 则 添加或更新Header 值Value
            else
                DefaultHeaders.AddOrUpdate(header, value, (a, b) => value);
        }
    }
}